package com.xuyiwei.xblog.business.system.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xuyiwei.xblog.core.base.constant.enums.CommonStatusEnum;
import com.xuyiwei.xblog.core.node.ZTreeNode;
import com.xuyiwei.xblog.core.util.Convert;
import com.xuyiwei.xblog.business.system.dao.RelationMapper;
import com.xuyiwei.xblog.business.system.dao.RoleMapper;
import com.xuyiwei.xblog.business.system.model.Relation;
import com.xuyiwei.xblog.business.system.model.Role;
import com.xuyiwei.xblog.business.system.service.IRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RelationMapper relationMapper;

    @Override
    @Transactional(readOnly = false)
    public void setAuthority(Long roleId, String ids) {

        // 删除该角色所有的权限
        this.roleMapper.deleteRolesById(roleId);

        // 添加新的权限
        Long [] idsAttr = Convert.toLongArray(true, Convert.toStrArray(",", ids));
        relationMapper.insertRoleByIds(roleId,idsAttr);
//        for (Long id : Convert.toLongArray(true, Convert.toStrArray(",", ids))) {
//            Relation relation = new Relation();
//            relation.setRoleid(roleId);
//            relation.setMenuid(id);
//            this.relationMapper.insert(relation);
//        }
    }

    @Override
    @Transactional(readOnly = false)
    public void delRoleById(Long roleId) {
        //删除角色
        this.roleMapper.deleteById(roleId);

        // 删除该角色所有的权限
        this.roleMapper.deleteRolesById(roleId);
    }

    @Override
    @Transactional(readOnly = false)
    public void delRoleByIds(List<Long> ids) {
        //删除角色
        List<Role> list = this.selectBatchIds(ids);
        for(Role role:list){
            role.setStatus(CommonStatusEnum.DELETE.getKey());
            role.updateById();
        }
        // 删除该角色所有的权限
        this.roleMapper.deleteRolesByIds(ids.toArray(new Long[0]));
    }

    @Override
    public List<Role> selectRoles(String condition) {
        return this.baseMapper.selectRoles(condition);
    }

    @Override
    public int deleteRolesById(Long roleId) {
        return this.baseMapper.deleteRolesById(roleId);
    }

    @Override
    public List<ZTreeNode> roleTreeList() {
        return this.baseMapper.roleTreeList();
    }

    @Override
    public List<ZTreeNode> roleTreeListByRoleId(String[] roleId) {
        return this.baseMapper.roleTreeListByRoleId(roleId);
    }

}
